<template>
  <div class="select-record">
    <div class="handle-btn">
        <BaseButton v-permission="{ btnCode: 'dlyh_d416_e20_2' }" style="margin: 10px" type="second" @click="exportVisaCard">导出签证单</BaseButton>
        <BaseButton v-permission="{ btnCode: 'dlyh_d416_e21_2' }" style="margin: 10px" type="second" @click="exportFileCard">导出档案卡</BaseButton>
    </div>
    <div class="tips">
        <i class="el-icon-info info-icon"></i>
        <span>已选择
            <span class="num">{{ selectLength }}</span>
            条养护记录，养护日期范围：{{ startDateAndEndDate[0] }} ~{{ startDateAndEndDate[1] }}
        </span>
    </div>
    <div class="table-warp">
        <BaseTable 
        slot="table"
        ref="table" 
        class="table"  
        :data="pageList" 
        :columns="columns"
        highlight-current-row 
        height="calc(100% - 73px)" 
        @sort-change="handleSortChange"
        >
            <template #code="{ scope: { row} }">
               <BaseButton type="text" @click="handleDetail(row)">  {{ row.recordCode }}</BaseButton>
            </template>
            <template #type="{ scope: { row} }">
                {{ row.type | value2Name(types) }}
            </template>
            <template #msStatus="{ scope: { row} }">
                <StateTag  :id="row.msStatus" type="jiliang"></StateTag>
            </template>
            <template #action="{ scope: { row} }">
                <BaseButton type="text" @click="handleDetail(row)">查看</BaseButton>
            </template>
        </BaseTable>
        <Pagination
            clas="pagination"
            :current-page.sync="page.pageNo"
            :page-size.sync="page.pageSize"
            :total="page.total"
            @size-change="classPageList"
            @current-change="classPageList"
        />
    </div>
  </div>
</template>
<script>
import { MetrologicalStatusOptions } from '@/views/maintenance-decision/constants'
import { value2Name } from '@/filters'
import StateTag from '../components/StateTag.vue'
import { ApplicationModel, MsMaintrecordModel } from '@/models'

import { ApplicationApi } from '@/api'
import downLoad from '@/utils/blob-download'

export default {
    components: {
        StateTag,
      
    },
    filters: {
        value2Name
    },
    props: {
        form: {
            type: Object,
            default: () => {}
        },
    },
    data() {
        return {
            model: new ApplicationModel(),
            msMaintrecordModel: new MsMaintrecordModel(),
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            list: [], // 全量list
            pageList: [], // 当前页面的list
            columns: [
                {
                    slot: 'code',
                    attrs: {
                        label: '养护记录编号',
                        prop: 'recordCode',
                        width: 150,
                    }
                },
                {
                    attrs: {
                        label: '养护日期',
                        prop: 'maintDate',
                        'show-overflow-tooltip': true,
                        sortable: 'custom',
                    }
                },
                {
                    slot: 'type',
                    attrs: {
                        label: '类型',
                        prop: 'type',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '施工单位',
                        prop: 'constructionUnitName',
                        'show-overflow-tooltip': true
                    }
                },
                
                {
                    attrs: {
                        label: '现场管理',
                        prop: 'managementUnitName',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '工作内容',
                        prop: 'workContent',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    slot: 'msStatus',
                    attrs: {
                        label: '计量状态',
                        prop: 'msStatus',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        label: '更新人',
                        prop: 'operatorName',
                    }
                },
                {
                    attrs: {
                        label: '更新时间',
                        prop: 'updateTime',
                        sortable: 'custom',
                    }
                },
                {
                    slot: 'action',
                    attrs: {
                        label: '操作',
                        width: '100',
                        fixed: 'right'
                    }
                }
            ],
            metrologicalStatusOptions: MetrologicalStatusOptions, // 计量状态
            query: {
                msStatusList: [1, 2, 3, 4],
                cycle: '',
                typeList: [],
                startDate: '',
                endDate: '',
                constructionUnitId: ''
            },
            contractCode: '',
            id: ''// 申请记录ID
        }
    },   
    computed: {
        // 页码数组
        pageArr() {
            const num = Math.ceil(this.list.length / this.page.pageSize)
            const arr = []
            for (let i = 1; i <= num; i++) {
                arr.push(i)
            }
            return arr
        },
        types() {
            return this.$store.state.types.maintenanceApplyTypes || []
        },
        selectLength() {
            return this.list.map(el => el.id).length || 0
        },
        startDateAndEndDate() {
            const dateList = this.list.map(el => el.maintDate)
            let start = ''
            let end = ''
            if (dateList.length && dateList.length === 1) {
                start = dateList[0]
                end = dateList[0]
            } else if (dateList.length && dateList.length >= 2) {
                const {minDate, maxDate} = this.findMinAndMaxDates(dateList)
                start = minDate
                end = maxDate
            } else {
                start = ''
                end = ''
            }
            return [start, end]
        }
    },
    watch: {
        form: {
            immediate: true,
            deep: true,
            handler(val) {
                this.query.cycle = this.form.cycle
                this.query.typeList = [this.form.type]
                this.query.constructionUnitId = this.form.constructionUnitId
                this.query.startDate = this.$dayjs(this.form.cycle).startOf('month').format('YYYY-MM-DD')
                this.query.endDate = this.$dayjs(this.form.cycle).endOf('month').format('YYYY-MM-DD')
                this.query.highwayCode = this.form.highwayCode
            }
        }
    },
    created() {
        this.getTypes()
    },
    methods: {
        getTypes() {
            this.$store.dispatch('types/query', 'maintenanceApplyTypes')
        },
        // 分页操作
        classPageList() {
            const pageSize = this.page.pageSize
            this.pageList = []
            const pageNo = this.page.pageNo
            const endIndext = pageNo * pageSize // 10  slice函数左闭右开
            const startIndex = endIndext - 1 - (pageSize - 1) // 0
            const list = [...this.list]
            this.pageList = list.slice(startIndex, endIndext)
        },
        // 排序, ascending升序 descending降序
        handleSortChange({ column, prop, order }) {  
            if (prop === 'updateTime') {
                if (order === 'ascending') {  
                    this.sortList('updateTime', 'ascending')
                    this.classPageList()
                } else {
                    // 默认排序
                    this.sortList('updateTime', 'descending')
                    this.classPageList()
                }
            }
            if (prop === 'maintDate') {
                if (order === 'ascending') {  
                    this.sortList('maintDate', 'ascending')
                    this.classPageList()
                } else {
                    this.sortList('maintDate', 'descending')
                    this.classPageList()
                }
            }
        },
        sortList(key, order) {
            this.list.sort(function(a, b) {
                var keyA = new Date(a[key])
                var keyB = new Date(b[key])
                // 正序排序
                if (order === 'ascending') {
                    if (keyA > keyB) return 1
                    if (keyA < keyB) return -1
                } else if (order === 'descending') {
                    if (keyA > keyB) return -1
                    if (keyA < keyB) return 1
                } else {
                    return 0
                }
                return 0
            })
        },
        // 查看养护记录详情查看养护记录详情
        handleDetail(row) {
            const targetUrl = this.$router.resolve({
                name: 'MaintenanceRecordManagementDetail',
                query: {
                    id: row.id,
                }
            }).href
            // 使用window.open在新标签页中打开该URL
            window.open(targetUrl, '_blank')
        },
        // 这里应该不用查，直接详情复制
        getList() {
            this.msMaintrecordModel.getList({...this.query}).then(res => {
                if (res) {
                    this.list = [...res].filter(el => { this.selectIds.indexOf(el.id) !== -1 })
                    this.firstSetDefualt = false
                    this.classPageList()
                }
            }
            )
        },
        // 导出签证卡
        exportVisaCard() {
            this.exportLoading = true
            const path = ApplicationApi.qzdxqPath
            const params = {
                id: this.id,
            }
            downLoad(path, {...params}, '', 'Excel', () => {
                this.exportLoading = false
            })
        },
        // 导出档案卡
        exportFileCard() {
            this.exportLoading = true
            const path = ApplicationApi.dakxqPath
            const params = {
                id: this.id,
            }
            downLoad(path, {...params}, '', 'Excel', () => {
                this.exportLoading = false
            })
        },
        findMinAndMaxDates(dates) {
            let minDate = new Date(dates[0])
            let maxDate = new Date(dates[0])
 
            for (let i = 1; i < dates.length; i++) {
                const date = new Date(dates[i])
                if (date < minDate) {
                    minDate = date
                } else if (date > maxDate) {
                    maxDate = date
                }
            }
 
            return { 
                minDate: this.$dayjs(minDate).format('YYYY-MM-DD'), 
                maxDate: this.$dayjs(maxDate).format('YYYY-MM-DD')
            }
        }
    }
}
</script>
<style scoped lang="scss">
.select-record{
  height:  calc(100% - 90px);
  width: 100%;
//   margin-top: 24px;、
  box-shadow: 0px 0px 4px 0px rgba(131, 145, 178, 0.2);
  position: relative;
  .handle-btn{
    display: flex;
    justify-content: flex-end;
  }
  .tips{
    margin:8px;
    background-color:rgba(4, 97, 255, 0.1) ;
    border: 1px solid rgba(4, 97, 255, 0.2);
    padding: 10px ;
    border-radius: 4px;
    .num,.info-icon{
        color: #409EFF;
    }
  }
  .table-warp{
    width:100%;
    height: 70%;
    position: relative;
    .table{
        width:100%;
        min-height: 400px;
    }
    .pagination{
        position: absolute;
        right: 24px;
        bottom: 16px;
    }
  }
 
  .model-title{
    width: 100%;
    padding: 16px 24px;
    border-bottom: 1px solid rgba(131, 145, 178, 0.1);
  }
  .btn{
    width: 100%;
    display: flex;
    justify-content: center;
    position: absolute;
    bottom: 24px;
  }
}

</style>
